<template>
  <a-card class="page-main page-main-admin" :bordered="false" v-title data-title="组管理">
    <div class="container">
      <div class="hte-head-content">
        <span class="bold-font">{{customParam.busKey=='dep'?'组织架构':'用户'}}组管理</span>
      </div>
      <div class="content-admin">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="组名称">
              <j-input placeholder="请输入组名称" v-model="queryParam.name"></j-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <!-- <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a> -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <!-- 高级查询区域 -->
      <!-- <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query> -->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
       <span v-if="selectedRowKeys.length == 1">
        <a-button @click="openGroup(selectionRows[0])" style="margin-left: 8px"> 组管理 <a-icon type="control" /></a-button>
      </span>
    </div>
 <div class="data-main" :class="{'shrinkage': shrinkageFlag}">          
        <div class="box-left ant-table-scroll" >
          <div class="tree-title">
            <span class="bold">目录</span>
            <a-icon type="menu-fold" @click="shrinkageFlag = !shrinkageFlag"  :title="!shrinkageFlag? '收缩目录' : '展开目录'"/>
          </div>
          <div class="tree" v-if="!shrinkageFlag"> 
            <a-input-search style="margin-bottom: 8px" v-model="searchValue" placeholder="搜索目录" @change="onChangeTree" />
            <a-tree                             
              :tree-data="treeData"
              :selectedKeys="treeSelectedKeys"
              @select="onSelectClass"
              @expand="onExpand"
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :replaceFields="{children:'children', title:'name', key:'id' }"
            >
             <template slot="title" slot-scope="{title}">
                <span v-if="title.indexOf(searchValue) > -1">
                  {{title.substr(0, title.indexOf(searchValue))}}
                  <span style="color: #f50">{{searchValue}}</span>
                  {{title.substr(title.indexOf(searchValue) + searchValue.length)}}
                </span>
                <span v-else>{{title}}</span>
              </template>
            </a-tree>
          </div>
        </div>
    <!-- table区域-begin -->
    <div class="box-right">
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
               <a-menu-item>
                <a @click="openGroup(record)">组管理</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>
    </div>
  </div>
  </div>
    <data-group-modal ref="modalForm" :customParam="customParam" @ok="modalFormOk"></data-group-modal>
    <div v-if="reloadGroup">
        <std-select-depart v-if="customParam.busKey=='dep'" ref="groupRef" v-show="false" @back="groupSave" :backInfo="{value:'busKey',text:'busKeyName'}"
     v-model="groups"  :multi="true" :replaceFields="{children:'children', title:'title', key:'id', value: 'id' }"></std-select-depart>
    <StdSelectMultiUser v-show="false" v-else-if="customParam.busKey=='user'" ref="groupRef" @back="groupSave" :backInfo="{value:'busKey',text:'busKeyName'}"  v-model="groups" :multiple="true"></StdSelectMultiUser>
    </div>
    
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import DataGroupModal from './modules/DataGroupModal'
  import { postAction, getAction } from '@/api/manage'
  export default {
    name: 'DataGroupList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      DataGroupModal,
      JInput: ()=>import('@/components/jeecg/JInput'),
      stdSelectDepart:()=> import('@/views/library/stdSample/StdSelectDepart'),
      StdSelectMultiUser:()=> import('@/views/library/stdSample/StdSelectMultiUser'),
    },
    data () {
      return {
        description: '组管理页面',
        // 表头
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'组名称',
            align:"center",
            dataIndex: 'name'
          },
           {
            title:'组全称',
            align:"center",
            dataIndex: 'nameAll'
          },
          {
            title:'组编码',
            align:"center",
            dataIndex: 'code'
          },
          {
            title:'排序',
            align:"center",
            dataIndex: 'orderNo'
          },
          {
            title:'备注',
            align:"center",
            dataIndex: 'remark'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: "/dataGroup/list",
          delete: "/dataGroup/delete",
          deleteBatch: "/dataGroup/deleteBatch",
          exportXlsUrl: "/dataGroup/exportXls",
          importExcelUrl: "/dataGroup/importExcel",
          buskeyList: "/dataGroup/buskeyList",
          buskeySave: "/dataGroup/buskeySave",
           getTree:"/dataGroup/groupTree",
        },
        dictOptions:{},
        superFieldList:[],
        isorter: {
        column: null,
        order: 'desc', },
        customParam:{
          busField:this.$route.params.busField,
          busKey: this.$route.params.busKey,
          busType:this.$route.query.busType,
        },
        groups:'',
        currentRow:{},
        disableMixinCreated:true,
        reloadGroup:true,
        shrinkageFlag:false,
        treeData: [],
        dataList: [],
        treeSelectedKeys: [],
        expandedKeys: [],
        searchValue: '',
        reloadTree:true,
        autoExpandParent: true,
      }
    },
    created() {
    this.getSuperFieldList();
     this.customParam={
        busField:this.$route.params.busField,
        busKey: this.$route.params.busKey,
        busType:this.$route.query.busType,
      }
      this.loadData(1)
      this.getTree()
    },
    mounted(){
     
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'name',text:'组名称',dictCode:''})
        fieldList.push({type:'string',value:'code',text:'组编码',dictCode:''})
        fieldList.push({type:'int',value:'orderNo',text:'排序',dictCode:''})
        fieldList.push({type:'string',value:'remark',text:'备注',dictCode:''})
        this.superFieldList = fieldList
      },
      openGroup(record){
        this.reloadGroup = false
        let dataGroupId = record.id
        this.currentRow = record
        this.groups = ''
        this.$nextTick(res=>{
         this.reloadGroup = true

          getAction(this.url.buskeyList,{dataGroupId}).then(res=>{
            if (res.code == 200) {
              let result = res.result||[]
              this.groups = result.map(item=>{return item.busKey}).join(",")
              this.$refs.groupRef.openModal()
              } else {
                this.$message.warning('操作异常:' + res.message)
              }
          })
        })
       

      },
      groupSave(buskeyList){
          if(!buskeyList || buskeyList.length == 0){
          this.$message.warning('请选择数据')
          return
        }
        postAction(this.url.buskeySave,{id:this.currentRow.id,buskeyList}).then(res=>{
           if (res.code == 200) {
              this.$message.success('操作成功')
            } else {
              this.$message.warning('操作异常:' + res.message)
            }
        })
      },
       customLoadDataAfter(){
          //列表加载后
        this.getTree()

      },
      customDeleteAfter(){
         //删除后
         this.customParam.parentId = '0'
         this.reloadTree = true
      },
      customSaveAfter(){
        //编辑保存后
        this.customParam.parentId = '0'
        this.reloadTree = true
      },
      onSelectClass(selectedKeys,e) {
      if(e&&!e.selected){
        selectedKeys = this.treeSelectedKeys
      }
      this.customParam.parentId = selectedKeys[0]
      this.treeSelectedKeys = selectedKeys
      this.loadData(1)
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onChangeTree(e) {
      const that = this
      const value = e.target.value;
      
      let expandedKeys = this.dataList
        .map(item => {
          if (item.title.indexOf(value) > -1) {
            return getParentKey(item.key, that.treeData);
          }
          return null;
        })
      expandedKeys =  expandedKeys.filter((item, i, self) => {
       return item && self.indexOf(item) === i
       });
      Object.assign(that, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      });
    },
    generateList(data){
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        const key = node.key;
        data[i].scopedSlots={title:'title'}
        this.dataList.push({ key, title: node.title });
        if (node.children) {
          this.generateList(node.children);
        }
    }
    },
     getTree(arg){
      if(this.reloadTree ) {
          let customParam = this.customParam
          getAction(this.url.getTree,{busField:customParam.busField,busKey:customParam.busKey,busType:customParam.busType}).then(res=>{
          if(res.code== 200){
             let treeData =  res.result || []
            let allTree = {children:null,title:'全部',name:'全部',id:'0',key:'0',value:'0'}
            treeData.unshift(allTree)
            this.generateList(treeData)
            this.treeData = treeData
            this.customParam.parentId = '0'
            this.treeSelectedKeys = ['0']
            this.reloadTree = false
          }else{
            this.$message.warning(res.message)
          }
        })
      }
        

      },
    }
  }
</script>
<style scoped lang="less">
  @import '~@assets/less/common.less';
    @import '~@assets/less/hte-main.less';
  @import '~@views/library/hteFile.less';
</style>